package com.keya.base;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Data
@Slf4j
public class WorkSpace {
    private File file;

    private String path;

    public WorkSpace(String path) {
        this.file = new File(path);
        this.path = path;
    }

    public void prepare() {
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public void clean() {
        try {
            if (file != null && file.exists()) {
                FileUtils.forceDelete(file);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    public String getPath(String first, String... more) {
        String ret = Paths.get(path, first).toString();
        if (more.length > 0) {
            ret = Paths.get(ret, more).toString();
        }
        return ret;
    }

    public Path createTmpFolder(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            fileName = UUID.randomUUID().toString();
        }

        Path p = Paths.get(path, fileName);
        p.toFile().mkdirs();
        return p;
    }

    public File createFile(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            fileName = UUID.randomUUID().toString();
        }

        Path p = Paths.get(path);
        p.toFile().mkdirs();
        File file = new File(Paths.get(path, fileName).toString());
        try {
            file.createNewFile();
        } catch (IOException e) {
        }
        return file;
    }
}
